package p2p.simulation;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseGraph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse.Mode;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.renderers.DefaultVertexLabelRenderer;

import p2p.gui.P2PWindow;
import p2p.logic.connection.client.Client;
import p2p.peer.Peer;

public class JungAdapter implements GraphUpdater{

	private Graph<String, String> graph;
	private VisualizationViewer<String, String> vv;
	private Layout<String, String> layout;
	public JungAdapter(List<Peer> peerList) {
		this.transformGraph(peerList);

		
		
		PeerManager.getInstance().addGraphUpdater(this);
	
	}
	
	public Graph<String,String> transformGraph(List<Peer> peerList){
		graph = new SparseGraph<String, String>();

		for (Peer peer : peerList) {
			
			graph.addVertex(peer.getPeerAsClient().getPort() + "");
			List<Client> neighbors = peer.getNeighbors();
			
			for (Client c : neighbors) {
				graph.addEdge(
						peer.getPeerAsClient().getPort() + "->" + c.getPort(),
						"" + peer.getPeerAsClient().getPort(), c.getPort() + "");
			}

		}
		return graph;
	}

	public BasicVisualizationServer<String, String> getVisualisation() {

		if (graph == null)
			graph = new SparseMultigraph<String, String>();
		
		layout = new CircleLayout<String, String>(graph);
		layout.setSize(new Dimension(300, 300));
		
		vv = new VisualizationViewer<String, String>(
				layout);
		
		vv.setPreferredSize(new Dimension(350, 350));
		vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
		
		vv.getPickedVertexState().addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) {
				Object obj = e.getItem();
				if (obj instanceof String){
					PeerManager.getInstance().leaveClient(obj);
				}
			}
		});
		vv.addMouseListener(new GraphMouselistener());
		return vv;

	}
	
	public void update(){
		layout.setGraph(transformGraph(PeerManager.getInstance().getPeerList()));
		this.vv.repaint();
	}

}
